{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Biome Level statistics for model: WK2"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "# import the libraries\n",
    "import ee\n",
    "import pandas as pd\n",
    "import os\n",
    "import numpy as np\n",
    "import random\n",
    "from random import sample\n",
    "import itertools \n",
    "import geopandas as gpd\n",
    "from sklearn.metrics import r2_score\n",
    "from termcolor import colored # this is allocate colour and fonts type for the print title and text\n",
    "from IPython.display import display, HTML"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "#set the working directory of local drive for Grid search result table loading\n",
    "# os.getcwd()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "# initialize the earth engine API\n",
    "ee.Initialize()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 1 Load the required composites and images"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "# load the basic maps that needed for the analysis\n",
    "# load the carbon concentration map\n",
    "carbonConcentration = ee.Image(\"users/leonidmoore/ForestBiomass/Biome_level_Wood_Carbon_Conentration_Map\")\n",
    "# load the root shoot ratio map\n",
    "rootShootRatio = ee.Image(\"users/leonidmoore/ForestBiomass/Root_shoot_ratio_Map\").unmask()\n",
    "# load the two composites tha will be used in the analysis\n",
    "compositeImage =ee.Image(\"users/leonidmoore/ForestBiomass/20200915_Forest_Biomass_Predictors_Image\")\n",
    "compositeImageNew = ee.Image(\"projects/crowtherlab/Composite/CrowtherLab_Composite_30ArcSec\")\n",
    "# load the biome layer \n",
    "biomeLayer = compositeImage.select(\"WWF_Biome\")\n",
    "# define a pixel area layer with unit km2\n",
    "pixelAreaMap = ee.Image.pixelArea().divide(10000);\n",
    "# define the boundary geography reference\n",
    "unboundedGeo = ee.Geometry.Polygon([-180, 88, 0, 88, 180, 88, 180, -88, 0, -88, -180, -88], None, False)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 2 Load the biomass density maps"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [],
   "source": [
    "# load the carbon density layers\n",
    "potentialDensity = ee.Image(\"users/nordmannmoore/ForestBiomass/RemoteSensingModel/EnsambleMaps/Predicted_WK2_Potential_density_Ensambled_Mean\").unmask()\n",
    "presentDensity =  ee.Image(\"users/leonidmoore/ForestBiomass/WalkerMap/reprojected_Walker_map_1km\").unmask()\n",
    "\n",
    "# define the standard projection\n",
    "stdProj = potentialDensity.projection();"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 3 Adjust the present and potential density maps"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [],
   "source": [
    "# load the present and potential forest cover\n",
    "presentForestCover = compositeImage.select('PresentTreeCover').unmask() # uniform with potential in the  0-1 scale\n",
    "potentialCoverAdjusted = ee.Image(\"users/leonidmoore/ForestBiomass/Bastin_et_al_2019_Potential_Forest_Cover_Adjusted\").unmask().rename('PotentialForestCover')\n",
    "# define the present and potential forest cover masks\n",
    "presentMask= presentForestCover.gt(0)\n",
    "potentialMask= potentialCoverAdjusted.gt(0)\n",
    "\n",
    "# check the difference of the two density maps\n",
    "potentialHigher = potentialDensity.multiply(pixelAreaMap).subtract(presentDensity.multiply(pixelAreaMap)).gte(0)\n",
    "potentialLower = potentialDensity.multiply(pixelAreaMap).subtract(presentDensity.multiply(pixelAreaMap)).lt(0)\n",
    "# replace the lower potential value by present biomass density value\n",
    "agbPotentialDensity = presentDensity.multiply(potentialLower).add(potentialDensity.multiply(potentialHigher))\n",
    "# add the root biomass to the AGB to get TGB\n",
    "tgbPotentialDensity = agbPotentialDensity.multiply(rootShootRatio).add(agbPotentialDensity)\n",
    "tgbPresentDensity = presentDensity.multiply(rootShootRatio).add(presentDensity)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 4 Partioning the potential cover into different landuse types"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Load all the landuse type layers\n",
    "croplandOrg = ee.Image(\"users/leonidmoore/ForestBiomass/HYDE31/cropland_Percent\").rename('cropland').divide(100).reproject(crs=stdProj);\n",
    "grazingOrg = ee.Image(\"users/leonidmoore/ForestBiomass/HYDE31/grazing_Percent\").rename('grazing').divide(100).reproject(crs=stdProj);\n",
    "pastureOrg = ee.Image(\"users/leonidmoore/ForestBiomass/HYDE31/pasture_Percent\").rename('pasture').divide(100).reproject(crs=stdProj);\n",
    "rangelandOrg = ee.Image(\"users/leonidmoore/ForestBiomass/HYDE31/rangeland_Percent\").rename('rangeland').divide(100).reproject(crs=stdProj);\n",
    "urbanOrg = compositeImage.select(['LandCoverClass_Urban_Builtup']).divide(100).unmask().reproject(crs=stdProj);\n",
    "snowIceOrg = compositeImageNew.select(['ConsensusLandCoverClass_Snow_Ice']).divide(100).unmask().reproject(crs=stdProj);\n",
    "openWaterOrg = compositeImageNew.select(['ConsensusLandCoverClass_Open_Water']).divide(100).unmask().reproject(crs=stdProj);\n",
    "# define the total landcover types\n",
    "sumCover = presentForestCover.add(pastureOrg).add(rangelandOrg).add(croplandOrg).add(urbanOrg).add(openWaterOrg).add(snowIceOrg);\n",
    "oneSubtract = ee.Image(1).subtract(sumCover);\n",
    "freeland = oneSubtract.multiply(oneSubtract.gte(0));\n",
    "# get the scale ratio for pixels with sumCover larger than 1\n",
    "scaleRatio = ee.Image(1).subtract(presentForestCover).divide(sumCover.subtract(presentForestCover)).multiply(oneSubtract.lt(0));\n",
    "# get the ratio of these three disturbed maps\n",
    "pasture = pastureOrg.multiply(scaleRatio).multiply(oneSubtract.lt(0)).add(pastureOrg.multiply(oneSubtract.gte(0))).unmask();\n",
    "rangeland = rangelandOrg.multiply(scaleRatio).multiply(oneSubtract.lt(0)).add(rangelandOrg.multiply(oneSubtract.gte(0))).unmask();\n",
    "cropland = croplandOrg.multiply(scaleRatio).multiply(oneSubtract.lt(0)).add(croplandOrg.multiply(oneSubtract.gte(0))).unmask();\n",
    "urban = urbanOrg.multiply(scaleRatio).multiply(oneSubtract.lt(0)).add(urbanOrg.multiply(oneSubtract.gte(0))).unmask();\n",
    "openWater = openWaterOrg.multiply(scaleRatio).multiply(oneSubtract.lt(0)).add(openWaterOrg.multiply(oneSubtract.gte(0))).unmask();\n",
    "snowIce = snowIceOrg.multiply(scaleRatio).multiply(oneSubtract.lt(0)).add(snowIceOrg.multiply(oneSubtract.gte(0))).unmask();\n",
    "sumTT = presentForestCover.add(pasture).add(rangeland).add(cropland).add(urban).add(freeland).add(openWater).add(snowIce).unmask();\n",
    "\n",
    "effectivePotentialMask = freeland.add(rangeland).add(pasture).add(cropland).add(urban).gt(0);\n",
    "# there are some pixels without any landcover survived but with open water and ice and snow. here we mask these pixels out\n",
    "sumlandCover = pastureOrg.add(rangelandOrg).add(croplandOrg).add(urbanOrg).add(freeland);\n",
    "restorationMap = potentialCoverAdjusted.subtract(presentForestCover).mask(effectivePotentialMask).unmask();\n",
    "\n",
    "# sum all these scaled layersv\n",
    "scaledSum = pasture.add(rangeland).add(cropland).add(urban).add(freeland);\n",
    "potentialCoverFinal = restorationMap.add(presentForestCover);\n",
    "# allocate the potential equally to each layer\n",
    "freelandPotentialCover = freeland.divide(scaledSum).multiply(restorationMap).unmask();\n",
    "rangelandPotentialCover = rangeland.divide(scaledSum).multiply(restorationMap).unmask();\n",
    "pasturePotentialCover = pasture.divide(scaledSum).multiply(restorationMap).unmask();\n",
    "croplandPotentialCover = cropland.divide(scaledSum).multiply(restorationMap).unmask();\n",
    "urbanPotentialCover = urban.divide(scaledSum).multiply(restorationMap).unmask();\n",
    "#  allocate the freeland potential in pixels with forest cover larger than 10% to conservation potential\n",
    "freelandForConsevation = freelandPotentialCover.multiply(presentForestCover.gte(0.1)).unmask();\n",
    "maximumPotentialCover = freelandForConsevation.add(presentForestCover);\n",
    "# calucate the reall freeland outside of forest\n",
    "freelandLeftMap = freelandPotentialCover.subtract(freelandForConsevation).unmask()# the left positive pixels are real freeland pixels"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 5 Partioning the biomass potential into different landuse types"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [],
   "source": [
    "# calculate the existing carbon, present potential carbon and absolute potential carbon in forests\n",
    "absoluteImage1 = tgbPresentDensity.multiply(pixelAreaMap).multiply(presentMask).divide(1000000000).rename('Present')\n",
    "absoluteImage3 = tgbPotentialDensity.multiply(pixelAreaMap).multiply(potentialCoverFinal.gt(0)).divide(1000000000).rename('AbsolutePotential')\n",
    "# get the sum of the potential covers\n",
    "potentialCoverSum = freelandLeftMap.add(rangelandPotentialCover).add(pasturePotentialCover).add(croplandPotentialCover).add(urbanPotentialCover)\n",
    "\n",
    "trueRestorationPotential = absoluteImage3.subtract(absoluteImage1).multiply(1000000000)\n",
    "ratioPotentialBiomassDensity = absoluteImage1.multiply(potentialCoverFinal.divide(presentForestCover))\n",
    "#  get the real for conservation potential\n",
    "realDensityIncreased = absoluteImage3.subtract(absoluteImage1).mask(absoluteImage3.subtract(ratioPotentialBiomassDensity).gt(0)).unmask()\n",
    "realDensityNotIncreased = absoluteImage3.subtract(absoluteImage1).mask(absoluteImage3.subtract(ratioPotentialBiomassDensity).lte(0)).unmask()\n",
    "trueReforestationPotential = realDensityNotIncreased.add(realDensityIncreased.multiply(ee.Image(1).subtract(presentForestCover.divide(potentialCoverFinal))))\n",
    "\n",
    "conservationPotentialPart1 = realDensityIncreased.multiply(presentForestCover.add(freelandForConsevation).divide(potentialCoverFinal))\n",
    "conservationPotentialPart2 = realDensityNotIncreased.multiply(freelandForConsevation.divide(potentialCoverFinal.subtract(presentForestCover)))\n",
    "\n",
    "# calculate the part of the potential inside the forest cover which was allocate to conservation potential.\n",
    "freelandForConservation1 = realDensityIncreased.multiply(freelandForConsevation.divide(potentialCoverFinal))\n",
    "freelandForConservation = freelandForConservation1.add(conservationPotentialPart2).rename('FreeToConservation')\n",
    "\n",
    "absoluteImage2 = conservationPotentialPart1.add(conservationPotentialPart2).add(absoluteImage1).rename('PresentPotential')\n",
    "\n",
    "trueReforestationPotential = absoluteImage3.subtract(absoluteImage2)\n",
    "\n",
    "absoluteImage4 = trueReforestationPotential.multiply(freelandLeftMap.divide(potentialCoverSum)).rename('FreelandPotential')\n",
    "absoluteImage5 = trueReforestationPotential.multiply(rangelandPotentialCover.divide(potentialCoverSum)).rename('RangelandPotential')\n",
    "absoluteImage6 = trueReforestationPotential.multiply(pasturePotentialCover.divide(potentialCoverSum)).rename('PasturePotential')\n",
    "absoluteImage7 = trueReforestationPotential.multiply(croplandPotentialCover.divide(potentialCoverSum)).rename('CroplandPotential')\n",
    "absoluteImage8 = trueReforestationPotential.multiply(urbanPotentialCover.divide(potentialCoverSum)).rename('UrbanPotential')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Calculate the potential numbers and write into local folder"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\u001b[1m\u001b[34mThe biomass partition results in biome: \n",
      "\u001b[0m\n"
     ]
    },
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>Present</th>\n",
       "      <th>PresentPotential</th>\n",
       "      <th>AbsolutePotential</th>\n",
       "      <th>FreelandPotential</th>\n",
       "      <th>RangelandPotential</th>\n",
       "      <th>PasturePotential</th>\n",
       "      <th>CroplandPotential</th>\n",
       "      <th>UrbanPotential</th>\n",
       "      <th>FreeToConservation</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>228.703254</td>\n",
       "      <td>260.819848</td>\n",
       "      <td>287.135435</td>\n",
       "      <td>5.181214</td>\n",
       "      <td>0.092218</td>\n",
       "      <td>8.726898</td>\n",
       "      <td>11.977674</td>\n",
       "      <td>0.337584</td>\n",
       "      <td>6.996705</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>9.864075</td>\n",
       "      <td>12.764340</td>\n",
       "      <td>22.992026</td>\n",
       "      <td>2.576771</td>\n",
       "      <td>0.024551</td>\n",
       "      <td>2.195959</td>\n",
       "      <td>5.363298</td>\n",
       "      <td>0.067107</td>\n",
       "      <td>0.844010</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>3.453565</td>\n",
       "      <td>5.199655</td>\n",
       "      <td>6.570279</td>\n",
       "      <td>0.498065</td>\n",
       "      <td>0.030771</td>\n",
       "      <td>0.489855</td>\n",
       "      <td>0.347180</td>\n",
       "      <td>0.004753</td>\n",
       "      <td>0.553577</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>49.234418</td>\n",
       "      <td>56.827702</td>\n",
       "      <td>76.974915</td>\n",
       "      <td>4.774627</td>\n",
       "      <td>0.026524</td>\n",
       "      <td>5.694217</td>\n",
       "      <td>9.159631</td>\n",
       "      <td>0.492214</td>\n",
       "      <td>2.514574</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>24.401686</td>\n",
       "      <td>26.763525</td>\n",
       "      <td>29.597274</td>\n",
       "      <td>1.281790</td>\n",
       "      <td>0.041848</td>\n",
       "      <td>0.869591</td>\n",
       "      <td>0.590690</td>\n",
       "      <td>0.049831</td>\n",
       "      <td>1.073061</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>5</th>\n",
       "      <td>45.302503</td>\n",
       "      <td>53.731483</td>\n",
       "      <td>56.739713</td>\n",
       "      <td>2.599304</td>\n",
       "      <td>0.000926</td>\n",
       "      <td>0.203195</td>\n",
       "      <td>0.191783</td>\n",
       "      <td>0.013024</td>\n",
       "      <td>3.543290</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>6</th>\n",
       "      <td>57.851302</td>\n",
       "      <td>77.731102</td>\n",
       "      <td>122.080894</td>\n",
       "      <td>9.834205</td>\n",
       "      <td>15.309867</td>\n",
       "      <td>10.899967</td>\n",
       "      <td>8.221473</td>\n",
       "      <td>0.084280</td>\n",
       "      <td>5.325583</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>7</th>\n",
       "      <td>4.801044</td>\n",
       "      <td>6.577623</td>\n",
       "      <td>29.067436</td>\n",
       "      <td>4.036702</td>\n",
       "      <td>7.382498</td>\n",
       "      <td>2.890485</td>\n",
       "      <td>8.065208</td>\n",
       "      <td>0.114920</td>\n",
       "      <td>0.225280</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>8</th>\n",
       "      <td>2.814477</td>\n",
       "      <td>3.634541</td>\n",
       "      <td>4.965390</td>\n",
       "      <td>0.390986</td>\n",
       "      <td>0.437783</td>\n",
       "      <td>0.264899</td>\n",
       "      <td>0.225039</td>\n",
       "      <td>0.012142</td>\n",
       "      <td>0.137102</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>9</th>\n",
       "      <td>4.397676</td>\n",
       "      <td>6.186691</td>\n",
       "      <td>12.819656</td>\n",
       "      <td>1.785759</td>\n",
       "      <td>2.932598</td>\n",
       "      <td>0.926101</td>\n",
       "      <td>0.974806</td>\n",
       "      <td>0.013701</td>\n",
       "      <td>0.234628</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>10</th>\n",
       "      <td>4.478712</td>\n",
       "      <td>7.134478</td>\n",
       "      <td>11.550023</td>\n",
       "      <td>4.407919</td>\n",
       "      <td>0.001460</td>\n",
       "      <td>0.000517</td>\n",
       "      <td>0.005332</td>\n",
       "      <td>0.000317</td>\n",
       "      <td>0.325521</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>11</th>\n",
       "      <td>4.798165</td>\n",
       "      <td>5.788099</td>\n",
       "      <td>11.741432</td>\n",
       "      <td>1.569860</td>\n",
       "      <td>0.023594</td>\n",
       "      <td>2.066978</td>\n",
       "      <td>2.206090</td>\n",
       "      <td>0.086812</td>\n",
       "      <td>0.281654</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>12</th>\n",
       "      <td>2.665324</td>\n",
       "      <td>4.114708</td>\n",
       "      <td>36.265757</td>\n",
       "      <td>15.315568</td>\n",
       "      <td>12.386541</td>\n",
       "      <td>1.183635</td>\n",
       "      <td>3.186526</td>\n",
       "      <td>0.078779</td>\n",
       "      <td>0.328276</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>13</th>\n",
       "      <td>2.159737</td>\n",
       "      <td>2.733499</td>\n",
       "      <td>3.239999</td>\n",
       "      <td>0.184181</td>\n",
       "      <td>0.001491</td>\n",
       "      <td>0.087385</td>\n",
       "      <td>0.218960</td>\n",
       "      <td>0.014482</td>\n",
       "      <td>0.137572</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>sum</th>\n",
       "      <td>444.925937</td>\n",
       "      <td>530.007293</td>\n",
       "      <td>711.740228</td>\n",
       "      <td>54.436950</td>\n",
       "      <td>38.692668</td>\n",
       "      <td>36.499681</td>\n",
       "      <td>50.733690</td>\n",
       "      <td>1.369946</td>\n",
       "      <td>22.520834</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "        Present  PresentPotential  AbsolutePotential  FreelandPotential  \\\n",
       "0    228.703254        260.819848         287.135435           5.181214   \n",
       "1      9.864075         12.764340          22.992026           2.576771   \n",
       "2      3.453565          5.199655           6.570279           0.498065   \n",
       "3     49.234418         56.827702          76.974915           4.774627   \n",
       "4     24.401686         26.763525          29.597274           1.281790   \n",
       "5     45.302503         53.731483          56.739713           2.599304   \n",
       "6     57.851302         77.731102         122.080894           9.834205   \n",
       "7      4.801044          6.577623          29.067436           4.036702   \n",
       "8      2.814477          3.634541           4.965390           0.390986   \n",
       "9      4.397676          6.186691          12.819656           1.785759   \n",
       "10     4.478712          7.134478          11.550023           4.407919   \n",
       "11     4.798165          5.788099          11.741432           1.569860   \n",
       "12     2.665324          4.114708          36.265757          15.315568   \n",
       "13     2.159737          2.733499           3.239999           0.184181   \n",
       "sum  444.925937        530.007293         711.740228          54.436950   \n",
       "\n",
       "     RangelandPotential  PasturePotential  CroplandPotential  UrbanPotential  \\\n",
       "0              0.092218          8.726898          11.977674        0.337584   \n",
       "1              0.024551          2.195959           5.363298        0.067107   \n",
       "2              0.030771          0.489855           0.347180        0.004753   \n",
       "3              0.026524          5.694217           9.159631        0.492214   \n",
       "4              0.041848          0.869591           0.590690        0.049831   \n",
       "5              0.000926          0.203195           0.191783        0.013024   \n",
       "6             15.309867         10.899967           8.221473        0.084280   \n",
       "7              7.382498          2.890485           8.065208        0.114920   \n",
       "8              0.437783          0.264899           0.225039        0.012142   \n",
       "9              2.932598          0.926101           0.974806        0.013701   \n",
       "10             0.001460          0.000517           0.005332        0.000317   \n",
       "11             0.023594          2.066978           2.206090        0.086812   \n",
       "12            12.386541          1.183635           3.186526        0.078779   \n",
       "13             0.001491          0.087385           0.218960        0.014482   \n",
       "sum           38.692668         36.499681          50.733690        1.369946   \n",
       "\n",
       "     FreeToConservation  \n",
       "0              6.996705  \n",
       "1              0.844010  \n",
       "2              0.553577  \n",
       "3              2.514574  \n",
       "4              1.073061  \n",
       "5              3.543290  \n",
       "6              5.325583  \n",
       "7              0.225280  \n",
       "8              0.137102  \n",
       "9              0.234628  \n",
       "10             0.325521  \n",
       "11             0.281654  \n",
       "12             0.328276  \n",
       "13             0.137572  \n",
       "sum           22.520834  "
      ]
     },
     "execution_count": 13,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# Stack the absolute biomass layers into an Image.\n",
    "absPotentialImage = absoluteImage1.addBands(absoluteImage2).addBands(absoluteImage3).addBands(absoluteImage4).addBands(absoluteImage5).addBands(absoluteImage6).addBands(absoluteImage7).addBands(absoluteImage8).addBands(freelandForConservation)\n",
    "# define the function to do the biome level statistics which could be applied by map      \n",
    "def biomeLevelStat(biome):\n",
    "    biomeMask = biomeLayer.eq(ee.Number(biome))\n",
    "    masked_img = absPotentialImage.mask(biomeMask)\n",
    "    output = masked_img.reduceRegion(reducer= ee.Reducer.sum(),\n",
    "                                     geometry= unboundedGeo,\n",
    "                                     crs='EPSG:4326',\n",
    "                                     crsTransform=[0.008333333333333333,0,-180,0,-0.008333333333333333,90],\n",
    "                                     maxPixels= 1e13)\n",
    "    return output#.getInfo().get('Present')\n",
    "\n",
    "\n",
    "biomeList = ee.List([1,2,3,4,5,6,7,8,9,10,11,12,13,14])\n",
    "statisticTable = biomeList.map(biomeLevelStat).getInfo()\n",
    "# transform into data frame\n",
    "outputTable = pd.DataFrame(statisticTable,columns =['Present','PresentPotential','AbsolutePotential','FreelandPotential','RangelandPotential','PasturePotential','CroplandPotential','UrbanPotential','FreeToConservation'])#.round(1)\n",
    "outputTable.loc['sum'] = outputTable.sum() \n",
    "outputTable.to_csv('Data/BiomeLevelStatistics/StatisticsForModels/WK2_Biome_Level_Statistics.csv',header=True,mode='w+')\n",
    "# display the output of the carbon partitioning\n",
    "print(colored('The biomass partition results in biome: \\n', 'blue', attrs=['bold']))\n",
    "outputTable.head(15)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {},
   "outputs": [],
   "source": [
    "# If you got the error 'EEException: Too many concurrent aggregations.', please re-run this chunck of code again."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\u001b[1m\u001b[34mThe biomass partition results in biome: \n",
      "\u001b[0m\n"
     ]
    },
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>Present</th>\n",
       "      <th>PresentPotential</th>\n",
       "      <th>AbsolutePotential</th>\n",
       "      <th>FreelandPotential</th>\n",
       "      <th>RangelandPotential</th>\n",
       "      <th>PasturePotential</th>\n",
       "      <th>CroplandPotential</th>\n",
       "      <th>UrbanPotential</th>\n",
       "      <th>FreeToConservation</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>279.026315</td>\n",
       "      <td>318.213429</td>\n",
       "      <td>350.322677</td>\n",
       "      <td>6.321928</td>\n",
       "      <td>0.112904</td>\n",
       "      <td>10.648275</td>\n",
       "      <td>14.614289</td>\n",
       "      <td>0.411853</td>\n",
       "      <td>8.536826</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>12.034080</td>\n",
       "      <td>15.572424</td>\n",
       "      <td>28.050551</td>\n",
       "      <td>3.143696</td>\n",
       "      <td>0.030174</td>\n",
       "      <td>2.679209</td>\n",
       "      <td>6.543178</td>\n",
       "      <td>0.081870</td>\n",
       "      <td>1.029688</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>4.214778</td>\n",
       "      <td>6.345370</td>\n",
       "      <td>8.017725</td>\n",
       "      <td>0.607741</td>\n",
       "      <td>0.037497</td>\n",
       "      <td>0.597594</td>\n",
       "      <td>0.423723</td>\n",
       "      <td>0.005801</td>\n",
       "      <td>0.675621</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>65.473775</td>\n",
       "      <td>75.570933</td>\n",
       "      <td>102.363358</td>\n",
       "      <td>6.348872</td>\n",
       "      <td>0.035218</td>\n",
       "      <td>7.572648</td>\n",
       "      <td>12.181126</td>\n",
       "      <td>0.654560</td>\n",
       "      <td>3.343514</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>32.450751</td>\n",
       "      <td>35.591410</td>\n",
       "      <td>39.357468</td>\n",
       "      <td>1.703475</td>\n",
       "      <td>0.055253</td>\n",
       "      <td>1.156060</td>\n",
       "      <td>0.785028</td>\n",
       "      <td>0.066243</td>\n",
       "      <td>1.426770</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>5</th>\n",
       "      <td>81.506726</td>\n",
       "      <td>96.672637</td>\n",
       "      <td>102.082644</td>\n",
       "      <td>4.676532</td>\n",
       "      <td>0.001545</td>\n",
       "      <td>0.364983</td>\n",
       "      <td>0.343573</td>\n",
       "      <td>0.023374</td>\n",
       "      <td>6.375726</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>6</th>\n",
       "      <td>70.579286</td>\n",
       "      <td>94.832547</td>\n",
       "      <td>148.940090</td>\n",
       "      <td>11.997803</td>\n",
       "      <td>18.678408</td>\n",
       "      <td>13.298212</td>\n",
       "      <td>10.030296</td>\n",
       "      <td>0.102825</td>\n",
       "      <td>6.497221</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>7</th>\n",
       "      <td>6.385594</td>\n",
       "      <td>8.748487</td>\n",
       "      <td>38.657734</td>\n",
       "      <td>5.368365</td>\n",
       "      <td>9.817388</td>\n",
       "      <td>3.844093</td>\n",
       "      <td>10.726567</td>\n",
       "      <td>0.152833</td>\n",
       "      <td>0.299656</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>8</th>\n",
       "      <td>3.434364</td>\n",
       "      <td>4.434945</td>\n",
       "      <td>6.058931</td>\n",
       "      <td>0.477081</td>\n",
       "      <td>0.534100</td>\n",
       "      <td>0.323271</td>\n",
       "      <td>0.274701</td>\n",
       "      <td>0.014832</td>\n",
       "      <td>0.167292</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>9</th>\n",
       "      <td>5.840211</td>\n",
       "      <td>8.216220</td>\n",
       "      <td>17.031680</td>\n",
       "      <td>2.372920</td>\n",
       "      <td>3.897961</td>\n",
       "      <td>1.230778</td>\n",
       "      <td>1.295587</td>\n",
       "      <td>0.018215</td>\n",
       "      <td>0.311565</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>10</th>\n",
       "      <td>8.057407</td>\n",
       "      <td>12.836420</td>\n",
       "      <td>20.782853</td>\n",
       "      <td>7.932725</td>\n",
       "      <td>0.002617</td>\n",
       "      <td>0.000929</td>\n",
       "      <td>0.009590</td>\n",
       "      <td>0.000571</td>\n",
       "      <td>0.585674</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>11</th>\n",
       "      <td>5.806925</td>\n",
       "      <td>7.005316</td>\n",
       "      <td>14.210004</td>\n",
       "      <td>1.899785</td>\n",
       "      <td>0.028662</td>\n",
       "      <td>2.501417</td>\n",
       "      <td>2.669762</td>\n",
       "      <td>0.105063</td>\n",
       "      <td>0.340951</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>12</th>\n",
       "      <td>3.225829</td>\n",
       "      <td>4.979839</td>\n",
       "      <td>43.887163</td>\n",
       "      <td>18.533593</td>\n",
       "      <td>14.989466</td>\n",
       "      <td>1.432747</td>\n",
       "      <td>3.856183</td>\n",
       "      <td>0.095335</td>\n",
       "      <td>0.397289</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>13</th>\n",
       "      <td>2.634881</td>\n",
       "      <td>3.334866</td>\n",
       "      <td>3.952792</td>\n",
       "      <td>0.224694</td>\n",
       "      <td>0.001817</td>\n",
       "      <td>0.106618</td>\n",
       "      <td>0.267129</td>\n",
       "      <td>0.017668</td>\n",
       "      <td>0.167837</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>sum</th>\n",
       "      <td>580.670921</td>\n",
       "      <td>692.354843</td>\n",
       "      <td>923.715669</td>\n",
       "      <td>71.609210</td>\n",
       "      <td>48.223010</td>\n",
       "      <td>45.756833</td>\n",
       "      <td>64.020733</td>\n",
       "      <td>1.751041</td>\n",
       "      <td>30.155630</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "        Present  PresentPotential  AbsolutePotential  FreelandPotential  \\\n",
       "0    279.026315        318.213429         350.322677           6.321928   \n",
       "1     12.034080         15.572424          28.050551           3.143696   \n",
       "2      4.214778          6.345370           8.017725           0.607741   \n",
       "3     65.473775         75.570933         102.363358           6.348872   \n",
       "4     32.450751         35.591410          39.357468           1.703475   \n",
       "5     81.506726         96.672637         102.082644           4.676532   \n",
       "6     70.579286         94.832547         148.940090          11.997803   \n",
       "7      6.385594          8.748487          38.657734           5.368365   \n",
       "8      3.434364          4.434945           6.058931           0.477081   \n",
       "9      5.840211          8.216220          17.031680           2.372920   \n",
       "10     8.057407         12.836420          20.782853           7.932725   \n",
       "11     5.806925          7.005316          14.210004           1.899785   \n",
       "12     3.225829          4.979839          43.887163          18.533593   \n",
       "13     2.634881          3.334866           3.952792           0.224694   \n",
       "sum  580.670921        692.354843         923.715669          71.609210   \n",
       "\n",
       "     RangelandPotential  PasturePotential  CroplandPotential  UrbanPotential  \\\n",
       "0              0.112904         10.648275          14.614289        0.411853   \n",
       "1              0.030174          2.679209           6.543178        0.081870   \n",
       "2              0.037497          0.597594           0.423723        0.005801   \n",
       "3              0.035218          7.572648          12.181126        0.654560   \n",
       "4              0.055253          1.156060           0.785028        0.066243   \n",
       "5              0.001545          0.364983           0.343573        0.023374   \n",
       "6             18.678408         13.298212          10.030296        0.102825   \n",
       "7              9.817388          3.844093          10.726567        0.152833   \n",
       "8              0.534100          0.323271           0.274701        0.014832   \n",
       "9              3.897961          1.230778           1.295587        0.018215   \n",
       "10             0.002617          0.000929           0.009590        0.000571   \n",
       "11             0.028662          2.501417           2.669762        0.105063   \n",
       "12            14.989466          1.432747           3.856183        0.095335   \n",
       "13             0.001817          0.106618           0.267129        0.017668   \n",
       "sum           48.223010         45.756833          64.020733        1.751041   \n",
       "\n",
       "     FreeToConservation  \n",
       "0              8.536826  \n",
       "1              1.029688  \n",
       "2              0.675621  \n",
       "3              3.343514  \n",
       "4              1.426770  \n",
       "5              6.375726  \n",
       "6              6.497221  \n",
       "7              0.299656  \n",
       "8              0.167292  \n",
       "9              0.311565  \n",
       "10             0.585674  \n",
       "11             0.340951  \n",
       "12             0.397289  \n",
       "13             0.167837  \n",
       "sum           30.155630  "
      ]
     },
     "execution_count": 19,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "deadWoodLitterRatio = ee.Image(\"users/leonidmoore/ForestBiomass/DeadWoodLitter/DeadWood_Litter_Ratio_Map\").unmask()\n",
    "\n",
    "# Stack the absolute biomass layers into an Image.\n",
    "absPotentialImage = absoluteImage1.addBands(absoluteImage2).addBands(absoluteImage3).addBands(absoluteImage4).addBands(absoluteImage5).addBands(absoluteImage6).addBands(absoluteImage7).addBands(absoluteImage8).addBands(freelandForConservation)\n",
    "# define the function to do the biome level statistics which could be applied by map      \n",
    "def biomeLevelStat(biome):\n",
    "    biomeMask = biomeLayer.eq(ee.Number(biome))\n",
    "    masked_img = absPotentialImage.mask(biomeMask).multiply(deadWoodLitterRatio)\n",
    "    output = masked_img.reduceRegion(reducer= ee.Reducer.sum(),\n",
    "                                     geometry= unboundedGeo,\n",
    "                                     crs='EPSG:4326',\n",
    "                                     crsTransform=[0.008333333333333333,0,-180,0,-0.008333333333333333,90],\n",
    "                                     maxPixels= 1e13)\n",
    "    return output#.getInfo().get('Present')\n",
    "\n",
    "\n",
    "biomeList = ee.List([1,2,3,4,5,6,7,8,9,10,11,12,13,14])\n",
    "statisticTable = biomeList.map(biomeLevelStat).getInfo()\n",
    "# transform into data frame\n",
    "outputTable = pd.DataFrame(statisticTable,columns =['Present','PresentPotential','AbsolutePotential','FreelandPotential','RangelandPotential','PasturePotential','CroplandPotential','UrbanPotential','FreeToConservation'])#.round(1)\n",
    "outputTable.loc['sum'] = outputTable.sum()\n",
    "outputTable.to_csv('Data/BiomeLevelStatistics/StatisticsForModels/WK2_Biome_Level_Statistics_with_Litter.csv',header=True,mode='w+')\n",
    "# display the output of the carbon partitioning\n",
    "print(colored('The biomass partition results in biome: \\n', 'blue', attrs=['bold']))\n",
    "outputTable.head(15)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# If you got the error 'EEException: Too many concurrent aggregations.', please re-run this chunck of code again."
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.5"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
